import LarkClient from "../../../lark-sdk/LarkClient.js";
import { AppConfig } from "../../lib/utility.js";
import { AuthorProfile, NoteContent, Query, SousuoJieguoBijiSchema, SousuoJieguoLiebiaoSchema, SousuoJieguoSchema, Top20MonitorSchema } from "../../lib/search.js";

var id =1

async function addUrlToFeishu(client: LarkClient, config: AppConfig, query: Query, contentdata: NoteContent,authorProfile: AuthorProfile,order: number) {
  try {

    const searchTime = Date.now();

    const screenshotFileToken = await client.uploadFileToBitable(
      contentdata.images, 
      config.larkAppToken
    );

    await client.appendDataToBitable(
      config.larkAppToken,
      config.bitableTop20MonitorTableID,
      [{
        [Top20MonitorSchema.id]: id, // ID
        [Top20MonitorSchema.order]: order,
        [Top20MonitorSchema.authorId]: authorProfile.redBookId,
        [Top20MonitorSchema.authorUrl]: {"link":authorProfile.authorUrl},
        [Top20MonitorSchema.noteUrl]: {"link":contentdata.link},
        [Top20MonitorSchema.fansCount]: authorProfile.fansCount,
        [Top20MonitorSchema.likes]: contentdata.likes,
        [Top20MonitorSchema.collects]: contentdata.collects,
        [Top20MonitorSchema.comments]: contentdata.comments,
        [Top20MonitorSchema.keywords]: query.keywords,
        [Top20MonitorSchema.publishTime]: contentdata.publishTime,
        // [Top20MonitorSchema.crawlTime]: searchTime,
        [Top20MonitorSchema.title]: contentdata.title,
        [Top20MonitorSchema.firstImage]: [{"file_token": screenshotFileToken, "file_name": contentdata.images}],
        [Top20MonitorSchema.imageCount]: contentdata.imagesCount,
        [Top20MonitorSchema.noteType]: contentdata.noteType,
        [Top20MonitorSchema.content]: contentdata.content,
      }]
    );

    id++;
    console.log(`已添加URL到飞书: ${contentdata.link}, 关键词: ${query.keywords}`);
  } catch (error) {
    console.error('添加URL到飞书失败:', error);
    throw error;
  }
}

/**
 * 更新飞书中的搜索时间
 */
async function updateSearchTime(client:LarkClient,config:AppConfig,recordId: string): Promise<void> {
  
  try {
    await client.updateBitable(
      config.larkAppToken,
      config.bitableSousuoGuanjianciTableID,
      recordId,
      { '最新搜索时间': Date.now() }
    );
  } catch (error) {
    console.error('更新搜索时间失败:', error);
  }

}


/**
  *  添加author profile 信息
*/
async function addAuthorProfile(client: LarkClient, config: AppConfig, recordId: string, authorProfile: string): Promise<void> {
  try {
    // 解析作者资料JSON
    const profile = JSON.parse(authorProfile);
    
    // 准备作者名称 - 从authorElement中获取或使用备用字段
    const authorName = profile.specificElements?.nickname || "";
    
    // 更新飞书中的笔记记录，添加作者资料
    await client.updateBitable(
      config.larkAppToken,
      config.bitableSousuoJieguoBijiTableID,
      recordId,
      {
        [SousuoJieguoBijiSchema.author]: authorName,
        [SousuoJieguoBijiSchema.authorId]: profile.id || profile.specificElements?.redBookId || "",
        [SousuoJieguoBijiSchema.authorFollows]: profile.social?.following || 0,
        [SousuoJieguoBijiSchema.authorFans]: profile.social?.followers || 0,
        [SousuoJieguoBijiSchema.authorInteraction]: 
          (profile.interactions?.likes || 0) + (profile.interactions?.collects || 0),
        [SousuoJieguoBijiSchema.likeCount]: profile.interactions?.likes || 0,
        [SousuoJieguoBijiSchema.collectCount]: profile.interactions?.collects || 0,
        [SousuoJieguoBijiSchema.commentCount]: profile.interactions?.comments || 0
      }
    );
    
    console.log(`已添加作者资料到飞书:`);
    console.log(`- 小红书ID: ${profile.id || profile.specificElements?.redBookId || "未获取"}`);
    console.log(`- 关注数: ${profile.social?.following || 0}`);
    console.log(`- 粉丝数: ${profile.social?.followers || 0}`);
    console.log(`- 笔记数: ${profile.social?.notesCount || 0}`);
    console.log(`- 记录ID: ${recordId}`);
  } catch (error) {
    console.error('添加作者资料失败:', error);
    throw error;
  }
}

export{addUrlToFeishu,updateSearchTime,addAuthorProfile}
